<template>
  <div class="websocket-test">
    <h1>WebSocket 测试工具</h1>

    <div class="control-panel">
      <div>
        <label for="ws-url">WebSocket 地址：</label>
        <input
            id="ws-url"
            v-model="wsUrl"
            placeholder="ws://localhost:8080"
        >
      </div>

      <div class="button-group">
        <button @click="connect" :disabled="isConnected">连接</button>
        <button @click="disconnect" :disabled="!isConnected">断开</button>
      </div>
    </div>

    <div class="message-panel">
      <div>
        <label for="message">发送消息：</label>
        <input
            id="message"
            v-model="messageToSend"
            :disabled="!isConnected"
            @keyup.enter="sendMessage"
        >
        <button @click="sendMessage" :disabled="!isConnected">发送</button>
      </div>

      <div class="message-box">
        <h3>接收消息：</h3>
        <div class="message-list">
          <div v-for="(msg, index) in receivedMessages" :key="index" class="message-item">
            {{ msg }}
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref } from 'vue';

export default {
  setup() {
    const wsUrl = ref('ws://localhost:9507/?EIO=4');
    const messageToSend = ref('42766["test","ff"]');
    const receivedMessages = ref([]);
    const socket = ref(null);
    const isConnected = ref(false);
    const timeoutTimer = ref(null); // 用于存储超时定时器

    const connect = () => {
      try {
        // 清除之前的超时检查（如果有）
        if (timeoutTimer.value) {
          clearTimeout(timeoutTimer.value);
        }

        socket.value = new WebSocket(wsUrl.value);
        addMessage(`连接中: ${wsUrl.value}...`);

        // 设置连接超时（5秒）
        const timeout = 5000; // 5秒超时
        timeoutTimer.value = setTimeout(() => {
          if (!isConnected.value && socket.value?.readyState === WebSocket.CONNECTING) {
            addMessage('连接超时，请检查服务器地址或网络');
            socket.value.close(); // 关闭正在尝试的连接
            isConnected.value = false;
          }
        }, timeout);

        socket.value.onopen = () => {
          isConnected.value = true;
          // 连接成功后清除超时检查
          if (timeoutTimer.value) {
            clearTimeout(timeoutTimer.value);
          }
          addMessage('连接已建立');
        };

        socket.value.onmessage = (event) => {
          // addMessage(`收到消息: ${event.data}`);
          // 检测PING消息（根据协议可能是"2"或"ping"）
          if (event.data === '2' || event.data.toLowerCase() === 'ping') {
            // 立即回复PONG
            socket.value.send('3'); // Socket.IO协议中3表示pong
            addMessage('[系统] 已回复PONG');
          } else {
            addMessage(`收到消息: ${event.data}`);
          }
        };

        socket.value.onclose = () => {
          isConnected.value = false;
          // 连接关闭时清除超时检查
          if (timeoutTimer.value) {
            clearTimeout(timeoutTimer.value);
          }
          addMessage('连接已关闭');
        };

        socket.value.onerror = (error) => {
          isConnected.value = false;
          // 发生错误时清除超时检查
          if (timeoutTimer.value) {
            clearTimeout(timeoutTimer.value);
          }
          addMessage(`错误: ${error.message}`);
        };

      } catch (error) {
        isConnected.value = false;
        if (timeoutTimer.value) {
          clearTimeout(timeoutTimer.value);
        }
        addMessage(`连接失败: ${error.message}`);
      }
    };

    const disconnect = () => {
      if (socket.value) {
        socket.value.close();
      }
    };

    const sendMessage = () => {
      if (socket.value && isConnected.value) {
        socket.value.send(messageToSend.value);
        addMessage(`发送: ${messageToSend.value}`);
        messageToSend.value = '';
      }
    };

    const addMessage = (message) => {
      // 修改为 unshift 添加到数组开头，而不是 push 添加到结尾
      receivedMessages.value.unshift(message);
      // 限制消息数量，避免内存问题
      if (receivedMessages.value.length > 100) {
        receivedMessages.value.pop(); // 改为移除最后一条（最旧的）
      }
    };

    return {
      wsUrl,
      messageToSend,
      receivedMessages,
      isConnected,
      connect,
      disconnect,
      sendMessage
    };
  }
};
</script>

<style scoped>
.websocket-test {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  font-family: Arial, sans-serif;
}

.control-panel {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f5f5;
  border-radius: 5px;
}

.message-panel {
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 5px;
}

input {
  padding: 8px;
  margin: 5px 0;
  width: 300px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

button {
  padding: 8px 15px;
  margin: 5px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

button:hover {
  background-color: #45a049;
}

button:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

.message-box {
  margin-top: 20px;
}

.message-list {
  max-height: 300px;
  overflow-y: auto;
  border: 1px solid #ddd;
  padding: 10px;
  background-color: white;
  border-radius: 4px;
}

.message-item {
  padding: 5px 0;
  border-bottom: 1px solid #eee;
}

.message-item:last-child {
  border-bottom: none;
}

.button-group {
  margin-top: 10px;
}
</style>